import React, { memo, useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { DjRadioRankingWrapper } from './style'
import DjRadioHeader from '@/components/djradio-header'
import { useAppSelector, shallowEqualApp, useAppDispatch } from '@/store'
import DjRankingCover from '@/components/djRanking-cover'
import { fetchDjRadioRankingAction } from '../../store/djradio'
import DjRadioPagination from '@/components/songs-pagination'

interface IProps {
  children?: ReactNode
}

const DjRadioRanking: React.FC<IProps> = () => {
  const { djRadioRanking, currentId, PER_PAGE_NUMBER, djRadioRankingTotal } = useAppSelector(
    (state) => ({
      djRadioRanking: state.djradio.djRadioRanking,
      currentId: state.djradio.currentId,
      PER_PAGE_NUMBER: state.djradio.PER_PAGE_NUMBER,
      djRadioRankingTotal: state.djradio.djRadioRankingTotal
    }),
    shallowEqualApp
  )
  const dispatch = useAppDispatch()

  const [currentPage, setCurrentPage] = useState(1)

  useEffect(() => {
    setCurrentPage(1)
    const cateId = currentId === 0 ? 3 : currentId
    dispatch(
      fetchDjRadioRankingAction({
        cateId,
        limit: PER_PAGE_NUMBER,
        offset: 0
      })
    )
  }, [dispatch, currentId, PER_PAGE_NUMBER])

  const onPageChange = (page: number) => {
    setCurrentPage(page)
    const offset = (page - 1) * PER_PAGE_NUMBER
    const cateId = currentId === 0 ? 3 : currentId
    dispatch(
      fetchDjRadioRankingAction({
        cateId,
        limit: PER_PAGE_NUMBER,
        offset
      })
    )
  }

  return (
    <DjRadioRankingWrapper>
      <DjRadioHeader title="电台排行榜"></DjRadioHeader>
      <div className="ranking-list">
        {djRadioRanking.map((item, index) => {
          return <DjRankingCover key={index} data={item} />
        })}
      </div>
      <DjRadioPagination
        currentPage={currentPage}
        total={djRadioRankingTotal || 0}
        onPageChange={onPageChange}
      />
    </DjRadioRankingWrapper>
  )
}

export default memo(DjRadioRanking)
